/**
 * 根据排期名称将旧系统的排期数据同步到新系统
 */

import * as fs from "fs";
import * as path from "path";

import { getDeviceInfoList, getDevicePlanLog } from "./api/oldApi";
import { downPlanByName } from "./util";
import config from "./config";

(async () => {
	try {
		const officeDeviceNames: string[] = process.argv.slice(2);

		if (officeDeviceNames.length === 0) {
			console.log("请指定设备的名称");
			process.exit(1);
		}

		for (let i = 0; i < officeDeviceNames.length; i++) {
			const officeDeviceName = officeDeviceNames[i];
			console.log(`开始下载【${officeDeviceName}】的数据`);

			const officeDeviceList = await getDeviceInfoList(officeDeviceName).then((res) => res.data.data);
			if (officeDeviceList.length === 0) {
				console.log(`没有找到对应【${officeDeviceName}】的设备名称数据`);
			} else {
				if (!fs.existsSync(config.MATERIALS_DIR)) fs.mkdirSync(config.MATERIALS_DIR);

				const targetDir = path.resolve(config.MATERIALS_DIR, officeDeviceName);
				if (!fs.existsSync(targetDir)) fs.mkdirSync(targetDir);

				let mapInfo: Record<string, any> = {};

				for (let j = 0; j < officeDeviceList.length; j++) {
					const device = officeDeviceList[j];
					console.log(`开始下载【${device.no}】的排期数据`);

					const devicePlanLogList = await getDevicePlanLog(device.id).then((res) => res.data.data);
					if (devicePlanLogList.length === 0) {
						console.log(`【${device.officeName}_${device.no}】的设备没有关联排期`);
						continue;
					}

					// const deviceNameAbsolute = path.resolve(targetDir, device.no.toString());
					// if (!fs.existsSync(deviceNameAbsolute)) fs.mkdirSync(deviceNameAbsolute);

					for (let k = 0; k < devicePlanLogList.length; k++) {
						const devicePlanLog = devicePlanLogList[k];
						console.log(`下载【${devicePlanLog.name}】排期数据`);
						// // devicePlanLog.planId
						// await downPlanByName(devicePlanLog.name, deviceNameAbsolute);

						if (!mapInfo[device.no]) {
							mapInfo[device.no] = {};
						}
						await downPlanByName(devicePlanLog.name, mapInfo[device.no], targetDir);
					}
				}

				await fs.promises.writeFile(`${targetDir}/mapInfo.json`, JSON.stringify(mapInfo, null, 2));
			}
		}
		console.log("success");
	} catch (err) {
		console.log("err: ", err);
	}
})();
